<?php

declare(strict_types=1);

namespace app\common\model;

use app\common\tool\excel\Export;

class UserCourse extends Base
{

    protected $name = 'user_course';
    /**
     * 学习记录
     */
    public static function studyRecord($param, $user)
    {
        try {
            $info = parent::where(['c_id' => $param['c_id'], 's_id' => $param['s_id'], 'uid' => $user->id])->find();
            switch ($param['type']) {
                case 1:
                    if (empty($info)) {
                        $data = [
                            'c_id' => $param['c_id'],
                            's_id' => $param['s_id'],
                            'uid' => $user->id,
                            'create_time' => time(),
                            'duration' => $param['duration']
                        ];
                        parent::create($data);
                    } else {
                        if ($param['duration'] > $info->duration) {
                            $info->duration = $param['duration'];
                            $info->save();
                        }
                    }
                    break;
                case 2:
                    if (empty($info)) {
                        $data = [
                            'c_id' => $param['c_id'],
                            's_id' => $param['s_id'],
                            'uid' => $user->id,
                            'create_time' => time(),
                            'status'=>2,
                            'duration' => $param['duration']
                        ];
                        parent::create($data);
                    } else {
                        if ($info->status == 1) {
                            $info->status = 2;
                            $info->duration = $param['duration'];
                            $info->save();
                        }
                    }
                    break;
                default:
                    return ['code' => -1, 'msg' => '学习失败！'];
                    break;
            }
            return ['code' => 1, 'msg' => '学习成功！'];
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
}
